package tree

type INode interface {
	Label() string
	Value() int64
	Parent() int64
	IsRoot() bool
}

type Tree struct {
	Title    string      `json:"label"`
	ID       int64       `json:"value"`
	ParentId int64       `json:"parent_id"`
	Data     interface{} `json:"data"`
	Children []Tree      `json:"children,omitempty"`
}

func ConvertToINodeArray[T INode](arr []T) (nodes []INode) {
	for _, item := range arr {
		nodes = append(nodes, item)
	}
	return
}

func MakeTree(nodes *[]INode) (trees []Tree) {
	trees = []Tree{}
	for _, node := range *nodes {
		if node.IsRoot() {
			child := Tree{
				Title:    node.Label(),
				ID:       node.Value(),
				ParentId: node.Parent(),
				Data:     node,
			}

			generateTree(&child, nodes)
			trees = append(trees, child)
		}
	}
	return
}

func generateTree(tree *Tree, nodes *[]INode) {
	for _, node := range *nodes {
		if tree.ID == node.Parent() {
			child := Tree{
				Title:    node.Label(),
				ID:       node.Value(),
				ParentId: node.Parent(),
				Data:     node,
			}

			generateTree(&child, nodes)
			tree.Children = append(tree.Children, child)
		}
	}
}
